var picsaveNS=function(c,f,b){var e=c.split(f||"."),g=b||window,d,a;for(d=0,a=e.length;d<a;d++){g=g[e[d]]=g[e[d]]||{}}return g};

picsaveNS("com.picsave.settings");

com.picsave.settings = function() {

	var pub = {};
	
	pub.bundle = null;
	pub.verifyValid = null;
	pub.verifyInvalid = null;
	pub.apiUrl = null;
	pub.apiDomain = null;
	pub.prefs = null;
	pub.PMhostname = 'chrome://picsave';
	pub.PMformSubmitURL = 'Account Info';

	pub.loadPrefs = function() {

		pub.bundle = pub.srGetStrBundle("chrome://picsave/locale/picsave.properties");
		pub.verifyValid = pub.bundle.GetStringFromName("verifyValid");
		pub.verifyInvalid = pub.bundle.GetStringFromName("verifyInvalid");
		pub.apiUrl = pub.bundle.GetStringFromName("apiUrl");
		pub.apiDomain = pub.bundle.GetStringFromName("apiDomain");
		pub.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
		var PMusername = '';
		var PMpassword = '';

		if (pub.prefs.getPrefType("extensions.picsave.prefs.loadLocation") == pub.prefs.PREF_INT){

			document.getElementById("picsave.prefs.loadLocation").selectedIndex = pub.prefs.getIntPref("extensions.picsave.prefs.loadLocation");

		}

		if (pub.prefs.getPrefType("extensions.picsave.prefs.email") == pub.prefs.PREF_STRING){

			document.getElementById("picsave.prefs.email").value = pub.prefs.getCharPref("extensions.picsave.prefs.email");
			PMusername = pub.prefs.getCharPref("extensions.picsave.prefs.email");

			if (PMusername!='') {

				try {

					if ("@mozilla.org/passwordmanager;1" in Components.classes) {

						try {

							var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);

							var e = passwordManager.enumerator;

							while (e.hasMoreElements()) {

								try {
								
									var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword);
									if (pass.host == pub.PMhostname && pass.user == PMusername) {

										PMpassword = pass.password;
										break;

									};
									
								} catch (ex) { };

							};


						} catch(ex) { };

					} else if ("@mozilla.org/login-manager;1" in Components.classes) {

						var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
						var logins = passwordManager.findLogins({}, pub.PMhostname, pub.PMformSubmitURL, null);
	      
						for (var i = 0; i < logins.length; i++) {

							if (logins[i].username == PMusername) {

								PMpassword = logins[i].password;
								break;

							};

						};

					};

				} catch(ex) { };

			};

			if (PMpassword!='') {

				document.getElementById("picsave.prefs.password").value = PMpassword;

			};

		}

		if (pub.prefs.getPrefType("extensions.picsave.prefs.gallery_title") == pub.prefs.PREF_STRING){

			document.getElementById("picsave.prefs.gallery_title").value = pub.prefs.getCharPref("extensions.picsave.prefs.gallery_title");

		};

		if (pub.prefs.getPrefType("extensions.picsave.prefs.image_format") == pub.prefs.PREF_INT){

			document.getElementById("picsave.prefs.image_format").value = pub.prefs.getIntPref("extensions.picsave.prefs.image_format");

		};

		if (pub.prefs.getPrefType("extensions.picsave.prefs.toolbarButton") == pub.prefs.PREF_INT ){

			if (pub.prefs.getIntPref("extensions.picsave.prefs.toolbarButton")==1) {

				document.getElementById('picsave.prefs.toolbarButton').selectedIndex = 0;

			} else {

				document.getElementById('picsave.prefs.toolbarButton').selectedIndex = 1;

			};

		};

		if (pub.prefs.getPrefType("extensions.picsave.prefs.sfw") == pub.prefs.PREF_INT ){

			if (pub.prefs.getIntPref("extensions.picsave.prefs.sfw")==1) {

				document.getElementById('picsave.prefs.sfw_radiogroup').selectedIndex = 0;

			} else {

				document.getElementById('picsave.prefs.sfw_radiogroup').selectedIndex = 1;

			};

		};

	};

	pub.savePrefs = function(){

		pub.prefs.setIntPref("extensions.picsave.prefs.toolbarButton",document.getElementById("picsave.prefs.toolbarButton").value);
		pub.prefs.setIntPref("extensions.picsave.prefs.loadLocation",document.getElementById("picsave.prefs.loadLocation").value);
		pub.prefs.setCharPref("extensions.picsave.prefs.email",document.getElementById("picsave.prefs.email").value);

		var PMusername = document.getElementById("picsave.prefs.email").value;
		var PMpassword = document.getElementById("picsave.prefs.password").value;

		if (PMusername!='') {

			if ("@mozilla.org/passwordmanager;1" in Components.classes) {

				var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);

				var e = passwordManager.enumerator;

				while (e.hasMoreElements()) {

					try {
							
						var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword);
						if (pass.host == pub.PMhostname && pass.user == PMusername) {

							passwordManager.removeUser(pub.PMhostname, PMusername);
							break;

						};
						
					} catch (ex) { };

				};

				if (PMpassword!='') {

					passwordManager.addUser(pub.PMhostname, PMusername, PMpassword);

				};

			} else if ("@mozilla.org/login-manager;1" in Components.classes) {

				var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);

				var logins = passwordManager.findLogins({}, pub.PMhostname, pub.PMformSubmitURL, null);
      
				for (var i = 0; i < logins.length; i++) {

					if (logins[i].username == PMusername) {

						passwordManager.removeLogin(logins[i]);
						break;

					};

				}

				if (PMpassword!='') {

					var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",Components.interfaces.nsILoginInfo,"init");
			  
					var extLoginInfo = new nsLoginInfo(pub.PMhostname, pub.PMformSubmitURL, null, PMusername, PMpassword,"","");

					passwordManager.addLogin(extLoginInfo);

				};

			};

		};

		pub.prefs.setCharPref("extensions.picsave.prefs.gallery_title",document.getElementById("picsave.prefs.gallery_title").value);
		pub.prefs.setIntPref("extensions.picsave.prefs.image_format",document.getElementById("picsave.prefs.image_format").value);

		if (document.getElementById('picsave.prefs.toolbarButton1').selected) {

			pub.prefs.setIntPref("extensions.picsave.prefs.toolbarButton",1);

		} else {

			pub.prefs.setIntPref("extensions.picsave.prefs.toolbarButton",0);

		};

		if (document.getElementById('picsave.prefs.sfw1').selected) {

			pub.prefs.setIntPref("extensions.picsave.prefs.sfw",1);

		} else {

			pub.prefs.setIntPref("extensions.picsave.prefs.sfw",0);

		};

	};

	pub.verifyLogin = function(email,password) {

		var verifyValid = pub.verifyValid;
		var verifyInvalid = pub.verifyInvalid;

		if (email!='' && password!='') {

			var str = 'sess_picsave_'+password+'y';
			var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);

			converter.charset = "UTF-8";  
			var result = {};  
			var data = converter.convertToByteArray(str, result);  
			var ch = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
			ch.init(ch.MD5);  
			ch.update(data, data.length);  
			var hash = ch.finish(false);  

			function toHexString(charCode) {
				return ("0" + charCode.toString(16)).slice(-2);
			};

			function ahex(i) {

				if (!isNaN(i)) {

					return toHexString(hash.charCodeAt(i))
					
				};
				
			};

			var passwordmd5 = [ahex(i) for (i in hash)].join("");

			
			var req = new XMLHttpRequest();
			req.open('GET', pub.apiUrl+"?f=logintest&e="+email+"&p="+passwordmd5, true);
			req.onreadystatechange = function(){ 

				if ( req.readyState == 4 ) {

					if ( req.status == 200 ) {

//						result = parseInt(req.responseText);
						result = req.responseText;
						result = eval("("+result+")");
						if (result.status==1) {
							document.getElementById('picsave.prefs.verify').label = verifyValid;
						} else {
							document.getElementById('picsave.prefs.verify').label = verifyInvalid;
							alert(result.err);
						};

					} else {

						alert('There was a problem with the request\nstatus=' + req.status);

					};

				};			

			};
			req.send(null);			

		} else {

			document.getElementById('picsave.prefs.verify').label = verifyInvalid;

		};

	};

	pub.toolbarButton = function(state) {

		var wm =  Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
		var win = wm.getMostRecentWindow("navigator:browser");
		var doc = win.document;

		var mainToolbar = doc.getElementById("nav-bar");

		if (state==1) {

			if (mainToolbar.currentSet.indexOf("picsavecom-button") == -1) {

				var set;

				if (mainToolbar.currentSet.indexOf("urlbar-container") != -1) {

					set = mainToolbar.currentSet.replace(/urlbar-container/, "picsavecom-button,urlbar-container");

				} else {

					set = currentset + ",picsavecom-button";

				};

				mainToolbar.setAttribute("currentset", set);

				mainToolbar.currentSet = set;

				doc.persist("nav-bar", "currentset");

				try {

					win.BrowserToolboxCustomizeDone(true);
					window.focus();

				} catch (e) { };

			};

		} else {

			if (mainToolbar.currentSet.indexOf("picsavecom-button") != -1) {

				var set;

				set = mainToolbar.currentSet.replace(/,picsavecom-button/, "");
				
				mainToolbar.setAttribute("currentset", set);

				mainToolbar.currentSet = set;

				doc.persist("nav-bar", "currentset");

				try {

					win.BrowserToolboxCustomizeDone(true);
					window.focus();

				} catch (e) { };

			};

		};

		pub.prefs.setIntPref("extensions.picsave.prefs.toolbarButton",state);

	};

	pub.srGetStrBundle = function(path) {

		var strBundle = null;

		var	bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService();
		bundleService = bundleService.QueryInterface(Components.interfaces.nsIStringBundleService);

		strBundle = bundleService.createBundle(path);

		return strBundle;

	};

	return pub;
	
}();